package iii.myangel;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import packet.SendEatData;
import packet.SendPicSound;

import DataClass.EatMedData;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class EatMedTimeActivity extends Activity {

	private final String tag = getClass().getName();
	private MediaRecorder mr; // 錄音器
	private ImageButton btnRecord; // 「錄音」按鈕
	private ImageButton btnStopRecord; // 「停止錄音」按鈕
	private ImageButton btnPlay; // 「播放」按鈕
	private ImageButton btnStopPlay; // 「停止播放」按鈕
	private MediaPlayer mp; // 播放器
	private ImageButton imgbtn, imgbtn2, imgbtn3; // picture button
	private Button btnSwitch;// 時間開關按鈕
	private Button btnTime;// 時間設定按鈕
	private final int TAKE_PICTURE = 1;
	static Boolean key1 = true, key2 = true, key3 = true;
	TimePickerDialog time;
	Calendar eatMedTime1, eatMedTime2, eatMedTime3, now = Calendar
			.getInstance();
	AlarmManager alarmManager1;
	PendingIntent pendingIntent1;
	private String audioPath1, audioPath2, audioPath3; // 錄音存檔路徑
	public String tmpFile1, tmpFile2, tmpFile3; // 照片存檔名稱
	public String SoundFile1, SoundFile2, SoundFile3;// 錄音存檔名稱
	public String picPath1, picPath2, picPath3;
	public Uri uri, uri2, uri3;
	public int playState1 = 0;
	Button btnBack, btnSwitch2, btnTime2; // 第2組按鈕
	ImageButton btnRecord2, btnPlay2, btnStopRecord2, btnStopPlay2, btnRecord3,
			btnPlay3, btnStopRecord3, btnStopPlay3;
	Button btnSwitch3, btnTime3; // 第3組按鈕
	CheckBox chkSUN1, chkMON1, chkTUE1, chkWED1, chkTHU1, chkFRI1, chkSAT1;
	CheckBox chkSUN2, chkMON2, chkTUE2, chkWED2, chkTHU2, chkFRI2, chkSAT2;
	CheckBox chkSUN3, chkMON3, chkTUE3, chkWED3, chkTHU3, chkFRI3, chkSAT3;
	public String state1 = "0", state2 = "0", state3 = "0";
	TextView lblTitle;
	int id;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_eatmedtime);
		findViews();
		findViews2();
		findViews3();
		findView4();

		// get oldMan id and name
		SharedPreferences sp = getSharedPreferences("olduser", 0);
		String tmp_print = "";
		{

			for (Entry<String, ?> entry : sp.getAll().entrySet()) {
				tmp_print += "{key: " + entry.getKey() + ", value: "
						+ entry.getValue() + "}";
			}
		}
		id = sp.getInt("id", 0);
		lblTitle.setText(sp.getString("name", "") + "設定");

		// 圖片跟錄音路徑
		tmpFile1 = id + "_image01.jpg";
		tmpFile2 = id + "_image02.jpg";
		tmpFile3 = id + "_image03.jpg";
		SoundFile1 = id + "_audio01.3gp";
		SoundFile2 = id + "_audio02.3gp";
		SoundFile3 = id + "_audio03.3gp";
		audioPath1 = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
				+ "/" + SoundFile1;
		audioPath2 = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
				+ "/" + SoundFile2;
		audioPath3 = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
				+ "/" + SoundFile3;
		btnBack = (Button) findViewById(R.id.btnBack);

		// 開始從SP讀資料 set1
		SharedPreferences set = getSharedPreferences(id + "set1", 0);
		btnSwitch.setText(set.getString("OnOff", state1).toString());
		if (btnSwitch.getText().equals("0")) {
			state1 = "0";
			btnSwitch.setText("已關");
		} else {
			state1 = "1";
			btnSwitch.setText("已開");
		}
		btnTime.setText(set.getString("EatTime", "時間"));
		chkSUN1.setChecked(set.getBoolean("sun", false));
		chkMON1.setChecked(set.getBoolean("mon", false));
		chkTUE1.setChecked(set.getBoolean("tue", false));
		chkWED1.setChecked(set.getBoolean("wed", false));
		chkTHU1.setChecked(set.getBoolean("thu", false));
		chkFRI1.setChecked(set.getBoolean("fri", false));
		chkSAT1.setChecked(set.getBoolean("sat", false));
		SoundFile1 = set.getString("soundF", SoundFile1);
		tmpFile1 = set.getString("picF", tmpFile1);

		// 開始從SP讀資料 set2
		SharedPreferences set2 = getSharedPreferences(id + "set2", 0);
		btnSwitch2.setText(set2.getString("OnOff", state2).toString());
		if (btnSwitch2.getText().equals("0")) {
			state2 = "0";
			btnSwitch2.setText("已關");
		} else {
			state2 = "1";
			btnSwitch2.setText("已開");
		}
		btnTime2.setText(set2.getString("EatTime", "時間"));
		chkSUN2.setChecked(set2.getBoolean("sun", false));
		chkMON2.setChecked(set2.getBoolean("mon", false));
		chkTUE2.setChecked(set2.getBoolean("tue", false));
		chkWED2.setChecked(set2.getBoolean("wed", false));
		chkTHU2.setChecked(set2.getBoolean("thu", false));
		chkFRI2.setChecked(set2.getBoolean("fri", false));
		chkSAT2.setChecked(set2.getBoolean("sat", false));
		SoundFile2 = set2.getString("soundF", SoundFile2);
		tmpFile2 = set2.getString("picF", tmpFile2);

		// 開始從SP讀資料 set3
		SharedPreferences set3 = getSharedPreferences(id + "set3", 0);
		btnSwitch3.setText(set3.getString("OnOff", state3).toString());
		if (btnSwitch3.getText().equals("0")) {
			state3 = "0";
			btnSwitch3.setText("已關");
		} else {
			state3 = "1";
			btnSwitch3.setText("已開");
		}
		btnTime3.setText(set3.getString("EatTime", "時間"));
		chkSUN3.setChecked(set3.getBoolean("sun", false));
		chkMON3.setChecked(set3.getBoolean("mon", false));
		chkTUE3.setChecked(set3.getBoolean("tue", false));
		chkWED3.setChecked(set3.getBoolean("wed", false));
		chkTHU3.setChecked(set3.getBoolean("thu", false));
		chkFRI3.setChecked(set3.getBoolean("fri", false));
		chkSAT3.setChecked(set3.getBoolean("sat", false));
		SoundFile3 = set3.getString("soundF", SoundFile3);
		tmpFile3 = set3.getString("picF", tmpFile3);

		// 上一頁按鈕
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Thread t = new Thread(new Runnable() {
					public void run() {
						try {
							SendEatData SED = new SendEatData();
							SED.id = id;// set 老人的ID
							// 存第1組
							SED.OnOff = state1;
							SED.EatTime = (String) btnTime.getText();
							SED.sun = chkSUN1.isChecked();
							SED.mon = chkMON1.isChecked();
							SED.tue = chkTUE1.isChecked();
							SED.wed = chkWED1.isChecked();
							SED.thu = chkTHU1.isChecked();
							SED.fri = chkFRI1.isChecked();
							SED.sat = chkSAT1.isChecked();

							SED.soundF1 = SoundFile1;
							SED.picF1 = tmpFile1;
							SED.setbPic(GetByte(tmpFile1));
							SED.setbSound(GetByte(SoundFile1));
							MainActivity.lcl.send(SED);
							Thread.sleep(1000);

							// SP 存法 1
							SharedPreferences SP = getSharedPreferences(id
									+ "set1", 0);
							Editor editor = SP.edit();
							editor.putString("OnOff", state1).commit();
							editor.putString("EatTime",
									(String) btnTime.getText()).commit();
							editor.putBoolean("sun", chkSUN1.isChecked())
									.commit();
							editor.putBoolean("mon", chkMON1.isChecked())
									.commit();
							editor.putBoolean("tue", chkTUE1.isChecked())
									.commit();
							editor.putBoolean("wed", chkWED1.isChecked())
									.commit();
							editor.putBoolean("thu", chkTHU1.isChecked())
									.commit();
							editor.putBoolean("fri", chkFRI1.isChecked())
									.commit();
							editor.putBoolean("sat", chkSAT1.isChecked())
									.commit();
							editor.putString("soundF", SoundFile1).commit();
							editor.putString("picF", tmpFile1).commit();

							// 存第2組
							SED.OnOff = state2;
							SED.EatTime = (String) btnTime2.getText();
							SED.sun = chkSUN2.isChecked();
							SED.mon = chkMON2.isChecked();
							SED.tue = chkTUE2.isChecked();
							SED.wed = chkWED2.isChecked();
							SED.thu = chkTHU2.isChecked();
							SED.fri = chkFRI2.isChecked();
							SED.sat = chkSAT2.isChecked();

							SED.soundF1 = SoundFile2;
							SED.picF1 = tmpFile2;
							SED.setbPic(GetByte(tmpFile2));
							SED.setbSound(GetByte(SoundFile2));
							MainActivity.lcl.send(SED);
							Thread.sleep(1000);

							
							// SP 存法 2
							SharedPreferences SP2 = getSharedPreferences(id
									+ "set2", 0);
							editor = SP2.edit();
							editor.putString("OnOff", state2).commit();
							editor.putString("EatTime",
									(String) btnTime2.getText()).commit();
							editor.putBoolean("sun", chkSUN2.isChecked())
									.commit();
							editor.putBoolean("mon", chkMON2.isChecked())
									.commit();
							editor.putBoolean("tue", chkTUE2.isChecked())
									.commit();
							editor.putBoolean("wed", chkWED2.isChecked())
									.commit();
							editor.putBoolean("thu", chkTHU2.isChecked())
									.commit();
							editor.putBoolean("fri", chkFRI2.isChecked())
									.commit();
							editor.putBoolean("sat", chkSAT2.isChecked())
									.commit();
							editor.putString("soundF", SoundFile2).commit();
							editor.putString("picF", tmpFile2).commit();

							// 存第3組
							SED.OnOff = state3;
							SED.EatTime = (String) btnTime3.getText();
							SED.sun = chkSUN3.isChecked();
							SED.mon = chkMON3.isChecked();
							SED.tue = chkTUE3.isChecked();
							SED.wed = chkWED3.isChecked();
							SED.thu = chkTHU3.isChecked();
							SED.fri = chkFRI3.isChecked();
							SED.sat = chkSAT3.isChecked();

							SED.soundF1 = SoundFile3;
							SED.picF1 = tmpFile3;
							SED.setbPic(GetByte(tmpFile3));
							SED.setbSound(GetByte(SoundFile3));
							MainActivity.lcl.send(SED);
							Thread.sleep(1000);

							// SP 存法 3
							SharedPreferences SP3 = getSharedPreferences(id
									+ "set3", 0);
							editor = SP3.edit();
							editor.putString("OnOff", state3).commit();
							editor.putString("EatTime",
									(String) btnTime3.getText()).commit();
							editor.putBoolean("sun", chkSUN3.isChecked())
									.commit();
							editor.putBoolean("mon", chkMON3.isChecked())
									.commit();
							editor.putBoolean("tue", chkTUE3.isChecked())
									.commit();
							editor.putBoolean("wed", chkWED3.isChecked())
									.commit();
							editor.putBoolean("thu", chkTHU3.isChecked())
									.commit();
							editor.putBoolean("fri", chkFRI3.isChecked())
									.commit();
							editor.putBoolean("sat", chkSAT3.isChecked())
									.commit();
							editor.putString("soundF", SoundFile3).commit();
							editor.putString("picF", tmpFile3).commit();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

				t.start();
				// MainActivity.lcl.send(SED);
				Intent intent = new Intent(EatMedTimeActivity.this,
						MainControlActivity.class);
				startActivity(intent);
			}
		});

		try {
			// 在img btn 上顯示照片 初始化
			ContentResolver cr = this.getContentResolver();
			File imageDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			uri = Uri.fromFile(new File(imageDir, tmpFile1));
			Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
			imgbtn.setImageBitmap(bitmap);

			uri2 = Uri.fromFile(new File(imageDir, tmpFile2));
			Bitmap bitmap2 = BitmapFactory.decodeStream(cr
					.openInputStream(uri2));
			imgbtn2.setImageBitmap(bitmap2);

			uri3 = Uri.fromFile(new File(imageDir, tmpFile3));
			Bitmap bitmap3 = BitmapFactory.decodeStream(cr
					.openInputStream(uri3));
			imgbtn3.setImageBitmap(bitmap3);
			// uri3 = Uri.fromFile(tmpFile3);
			// Bitmap bitmap3 =
			// BitmapFactory.decodeStream(cr.openInputStream(uri3));
			// imgbtn3.setImageBitmap(bitmap3);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void findView4() {
		// 第3格
		btnSwitch3 = (Button) findViewById(R.id.btnSwitch3);
		btnSwitch3.setOnClickListener(btnSwitch3_click);
		btnTime3 = (Button) findViewById(R.id.btnTime3);
		btnTime3.setOnClickListener(btnTime3_click);
		imgbtn3 = (ImageButton) findViewById(R.id.imgbtn3);
		btnRecord3 = (ImageButton) findViewById(R.id.btnRecord3);
		btnPlay3 = (ImageButton) findViewById(R.id.btnPlay3);
		btnStopRecord3 = (ImageButton) findViewById(R.id.btnStopRecord3);
		btnStopPlay3 = (ImageButton) findViewById(R.id.btnStopPlay3);
		imgbtn3.setOnClickListener(imgbtn_click3);

		// 按下「錄音」按鈕 (3)
		btnRecord3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				btnRecord3.setEnabled(false);
				btnPlay3.setEnabled(false);
				// btnRecord3.setText("錄音中");
				playState1 = 1;
				Toast.makeText(EatMedTimeActivity.this, "錄音開始",
						Toast.LENGTH_LONG).show();

				if (mr == null)
					mr = new MediaRecorder();
				else
					mr.reset();
				try {
					mr.setAudioSource(MediaRecorder.AudioSource.MIC);
					mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
					mr.setOutputFile(audioPath3);
					mr.prepare();
					mr.start();

				} catch (Exception e) {
					Log.e(tag, e.toString());
				}
				Toast.makeText(EatMedTimeActivity.this, audioPath3.toString(),
						Toast.LENGTH_SHORT).show();
			}
		});

		// 按下「停止錄音」「播放」按鈕 (3)
		btnStopRecord3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (playState1 == 1) {
					if (mr != null) {
						mr.stop();
						mr.release();
						mr = null;
						btnRecord3.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "錄音停止",
								Toast.LENGTH_LONG).show();
						// btnRecord3.setText("錄音");
					}
				} else if (playState1 == 2) {
					if (mp != null) {
						mp.stop();
						// btnPlay3.setText("播放");
						btnPlay3.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "播放停止",
								Toast.LENGTH_LONG).show();
					}
				}
				btnRecord3.setEnabled(true);
				btnPlay3.setEnabled(true);
			}
		});

		// 按下PLAY按鈕 (3)
		btnPlay3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				playAudio(audioPath3);
				btnPlay3.setEnabled(false);
				// btnPlay3.setText("播放中");
				playState1 = 2;
				Toast.makeText(EatMedTimeActivity.this, "播放開始",
						Toast.LENGTH_LONG).show();
				btnRecord3.setEnabled(false);
				btnPlay3.setEnabled(false);
			}
		});
	}

	private void findViews3() {
		// 第2格
		btnSwitch2 = (Button) findViewById(R.id.btnSwitch2);
		btnSwitch2.setOnClickListener(btnSwitch2_click);
		btnTime2 = (Button) findViewById(R.id.btnTime2);
		btnTime2.setOnClickListener(btnTime2_click);
		imgbtn2 = (ImageButton) findViewById(R.id.imgbtn2);
		imgbtn2.setOnClickListener(imgbtn_click2);
		btnRecord2 = (ImageButton) findViewById(R.id.btnRecord2);
		btnPlay2 = (ImageButton) findViewById(R.id.btnPlay2);
		btnStopRecord2 = (ImageButton) findViewById(R.id.btnStopRecord2);
		btnStopPlay2 = (ImageButton) findViewById(R.id.btnStopPlay2);
		btnRecord2.setOnClickListener(new OnClickListener() {

			// 按下「錄音」按鈕 (2)
			@Override
			public void onClick(View v) {
				btnRecord2.setEnabled(false);
				btnPlay2.setEnabled(false);
				// btnRecord2.setText("錄音中");
				playState1 = 1;
				Toast.makeText(EatMedTimeActivity.this, "錄音開始",
						Toast.LENGTH_LONG).show();

				if (mr == null)
					mr = new MediaRecorder();
				else
					mr.reset();
				try {
					mr.setAudioSource(MediaRecorder.AudioSource.MIC);
					mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
					mr.setOutputFile(audioPath2);
					mr.prepare();
					mr.start();
				} catch (Exception e) {
					Log.e(tag, e.toString());
				}
			}
		});

		// 按下「停止錄音」「播放」按鈕 (2)
		btnStopRecord2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (playState1 == 1) {
					if (mr != null) {
						mr.stop();
						mr.release();
						mr = null;
						btnRecord2.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "錄音停止",
								Toast.LENGTH_LONG).show();
						// btnRecord2.setText("錄音");
					}
				} else if (playState1 == 2) {
					if (mp != null) {
						mp.stop();
						// btnPlay2.setText("播放");
						btnPlay2.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "播放停止",
								Toast.LENGTH_LONG).show();
					}
				}
				btnRecord2.setEnabled(true);
				btnPlay2.setEnabled(true);
			}
		});

		// 按下PLAY按鈕 (2)
		btnPlay2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				playAudio(audioPath2);
				btnPlay2.setEnabled(false);
				// btnPlay2.setText("播放中");
				playState1 = 2;
				Toast.makeText(EatMedTimeActivity.this, "播放開始",
						Toast.LENGTH_LONG).show();
				btnRecord2.setEnabled(false);
				btnPlay2.setEnabled(false);
			}
		});

	}

	private void findViews2() {
		// check box第1格
		chkSUN1 = (CheckBox) findViewById(R.id.chkSUN1);
		chkMON1 = (CheckBox) findViewById(R.id.chkMON1);
		chkTUE1 = (CheckBox) findViewById(R.id.chkTUE1);
		chkWED1 = (CheckBox) findViewById(R.id.chkWED1);
		chkTHU1 = (CheckBox) findViewById(R.id.chkTHU1);
		chkFRI1 = (CheckBox) findViewById(R.id.chkFRI1);
		chkSAT1 = (CheckBox) findViewById(R.id.chkSAT1);

		// check box第2格
		chkSUN2 = (CheckBox) findViewById(R.id.chkSUN2);
		chkMON2 = (CheckBox) findViewById(R.id.chkMON2);
		chkTUE2 = (CheckBox) findViewById(R.id.chkTUE2);
		chkWED2 = (CheckBox) findViewById(R.id.chkWED2);
		chkTHU2 = (CheckBox) findViewById(R.id.chkTHU2);
		chkFRI2 = (CheckBox) findViewById(R.id.chkFRI2);
		chkSAT2 = (CheckBox) findViewById(R.id.chkSAT2);

		// check box第3格
		chkSUN3 = (CheckBox) findViewById(R.id.chkSUN3);
		chkMON3 = (CheckBox) findViewById(R.id.chkMON3);
		chkTUE3 = (CheckBox) findViewById(R.id.chkTUE3);
		chkWED3 = (CheckBox) findViewById(R.id.chkWED3);
		chkTHU3 = (CheckBox) findViewById(R.id.chkTHU3);
		chkFRI3 = (CheckBox) findViewById(R.id.chkFRI3);
		chkSAT3 = (CheckBox) findViewById(R.id.chkSAT3);
	}

	private void findViews() {
		// 第1組按鈕
		lblTitle = (TextView) findViewById(R.id.lblTitle);
		btnSwitch = (Button) findViewById(R.id.btnSwitch);
		btnSwitch.setOnClickListener(btnSwitch_click);
		btnTime = (Button) findViewById(R.id.btnTime);
		btnTime.setOnClickListener(btnTime_click);
		btnRecord = (ImageButton) findViewById(R.id.btnRecord);
		btnStopRecord = (ImageButton) findViewById(R.id.btnStopRecord);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnStopPlay = (ImageButton) findViewById(R.id.btnStopPlay);
		imgbtn = (ImageButton) findViewById(R.id.imgbtn1);
		imgbtn.setOnClickListener(imgbtn_click);

		// 按下「錄音」按鈕 (1)
		btnRecord.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				btnRecord.setEnabled(false);
				btnPlay.setEnabled(false);
				// btnRecord.setText("錄音中");
				playState1 = 1;
				Toast.makeText(EatMedTimeActivity.this, "錄音開始",
						Toast.LENGTH_LONG).show();

				if (mr == null)
					mr = new MediaRecorder();
				else
					mr.reset();
				try {
					mr.setAudioSource(MediaRecorder.AudioSource.MIC);
					mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
					mr.setOutputFile(audioPath1);
					mr.prepare();
					mr.start();
					Toast.makeText(EatMedTimeActivity.this, audioPath1,
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					Log.e(tag, e.toString());
				}
			}
		});

		// 按下「停止錄音」「播放」按鈕 (1)
		btnStopRecord.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (playState1 == 1) {
					if (mr != null) {
						mr.stop();
						mr.release();
						mr = null;
						btnRecord.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "錄音停止",
								Toast.LENGTH_LONG).show();
						// btnRecord.setText("錄音");
					}
				} else if (playState1 == 2) {
					if (mp != null) {
						mp.stop();
						// btnPlay.setText("播放");
						btnPlay.setEnabled(true);
						Toast.makeText(EatMedTimeActivity.this, "播放停止",
								Toast.LENGTH_LONG).show();
					}
				}
				btnRecord.setEnabled(true);
				btnPlay.setEnabled(true);
			}
		});

		// 按下PLAY按鈕 (1)
		btnPlay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				playAudio(audioPath1);
				btnPlay.setEnabled(false);
				// btnPlay.setText("播放中");
				playState1 = 2;
				Toast.makeText(EatMedTimeActivity.this, "播放開始",
						Toast.LENGTH_LONG).show();
				Toast.makeText(EatMedTimeActivity.this, audioPath1,
						Toast.LENGTH_LONG).show();
				btnRecord.setEnabled(false);
				btnPlay.setEnabled(false);
			}
		});
	}

	// 播放方法
	private void playAudio(String path) {
		if (mp == null)
			mp = new MediaPlayer();
		try {
			mp.reset();
			mp.setDataSource(path);
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mp.prepare();
			mp.start();
		} catch (Exception e) {
			Log.e(tag, e.toString());
		}
	}

	// 第1個img btn
	OnClickListener imgbtn_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isIntentAvailable(EatMedTimeActivity.this,
					MediaStore.ACTION_IMAGE_CAPTURE)) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 11);
			} else {
				Toast.makeText(EatMedTimeActivity.this, "No Camera",
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	// 第2個img btn
	OnClickListener imgbtn_click2 = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isIntentAvailable(EatMedTimeActivity.this,
					MediaStore.ACTION_IMAGE_CAPTURE)) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 22);
			} else {
				Toast.makeText(EatMedTimeActivity.this, "No Camera",
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	// 第3個img btn
	OnClickListener imgbtn_click3 = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isIntentAvailable(EatMedTimeActivity.this,
					MediaStore.ACTION_IMAGE_CAPTURE)) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 33);
			} else {
				Toast.makeText(EatMedTimeActivity.this, "No Camera",
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	// 檢查INTENT是否可執行拍照
	public boolean isIntentAvailable(Context context, String action) {
		PackageManager packageManager = context.getPackageManager();
		Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	// 拍照後回傳
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			if (requestCode == 11) {

				Bitmap imageA = (Bitmap) data.getExtras().get("data");
				imgbtn.setImageBitmap(imageA);
				saveImage(imageA, tmpFile1);

			} else if (requestCode == 22) {
				Bitmap imageB = (Bitmap) data.getExtras().get("data");
				imgbtn2.setImageBitmap(imageB);
				saveImage(imageB, tmpFile2);
				picPath2 = new File(
						Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
						tmpFile2).toString();
			} else if (requestCode == 33) {
				Bitmap imageB = (Bitmap) data.getExtras().get("data");
				imgbtn3.setImageBitmap(imageB);
				saveImage(imageB, tmpFile3);
				picPath3 = new File(
						Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
						tmpFile3).toString();
			}

		} else {
			return;
		}
	}

	// 儲存圖片
	private void saveImage(Bitmap image, String file) {
		File imageDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		Toast.makeText(this, imageDir.toString(), Toast.LENGTH_SHORT).show();
		if (!imageDir.exists()) {
			imageDir.mkdirs();
		}

		File imageFile = new File(imageDir, file);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(imageFile));

			image.compress(Bitmap.CompressFormat.JPEG, 90, bos);
			bos.flush();
			bos.close();
			Toast.makeText(this, imageFile.toString(), Toast.LENGTH_SHORT)
					.show();

			picPath2 = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					tmpFile2).toString();
			picPath3 = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					tmpFile3).toString();
		} catch (Exception ioe) {
			Log.e(getPackageName(), ioe.toString());
		}
		String[] paths = { imageFile.toString() };
		callMediaScanner(paths);
	}

	private void callMediaScanner(String[] paths) {
		MediaScannerConnection.scanFile(this, paths, null,
				new MediaScannerConnection.OnScanCompletedListener() {
					public void onScanCompleted(String path, Uri uri) {
						Log.i("ExternalStorageEx", "Scanned " + path + ":");
						Log.i("ExternalStorageEx", "-> uri=" + uri);
					}
				});
	}

	// 時間按鈕方法1
	OnClickListener btnTime_click = new OnClickListener() {

		@Override
		public void onClick(View btn) {
			// TODO Auto-generated method stub
			eatMedTime1 = Calendar.getInstance();
			String pattern = "kk:mm";
			final SimpleDateFormat fm = new SimpleDateFormat(pattern);
			// create TimeDialog
			Dialog timeDialog = new TimePickerDialog(EatMedTimeActivity.this,
					new TimePickerDialog.OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							// txtTime.setText(hourOfDay+":"+minute);//show time
							// on txtView
							eatMedTime1.set(Calendar.HOUR_OF_DAY, hourOfDay);
							eatMedTime1.set(Calendar.MINUTE, minute);
							btnTime.setText(fm.format(eatMedTime1.getTime()));
							Toast.makeText(EatMedTimeActivity.this,
									fm.format(eatMedTime1.getTime()),
									Toast.LENGTH_SHORT).show();
						}
					}, eatMedTime1.get(Calendar.HOUR),
					eatMedTime1.get(Calendar.MINUTE), false);// get time
			timeDialog.setTitle("Select Time");// dialog Title
			timeDialog.show();// show TimeDialog
		}
	};

	// 時間按鈕方法2
	OnClickListener btnTime2_click = new OnClickListener() {

		@Override
		public void onClick(View btn) {
			// TODO Auto-generated method stub
			eatMedTime2 = Calendar.getInstance();
			String pattern = "kk:mm";
			final SimpleDateFormat fm = new SimpleDateFormat(pattern);
			// create TimeDialog
			Dialog timeDialog = new TimePickerDialog(EatMedTimeActivity.this,
					new TimePickerDialog.OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							// txtTime.setText(hourOfDay+":"+minute);//show time
							// on txtView
							eatMedTime2.set(Calendar.HOUR_OF_DAY, hourOfDay);
							eatMedTime2.set(Calendar.MINUTE, minute);
							btnTime2.setText(fm.format(eatMedTime2.getTime()));
							Toast.makeText(EatMedTimeActivity.this,
									fm.format(eatMedTime2.getTime()),
									Toast.LENGTH_SHORT).show();
						}
					}, eatMedTime2.get(Calendar.HOUR),
					eatMedTime2.get(Calendar.MINUTE), false);// get time
			timeDialog.setTitle("Select Time");// dialog Title
			timeDialog.show();// show TimeDialog
		}
	};

	// 時間按鈕方法3
	OnClickListener btnTime3_click = new OnClickListener() {

		@Override
		public void onClick(View btn) {
			// TODO Auto-generated method stub
			eatMedTime3 = Calendar.getInstance();
			String pattern = "kk:mm";
			final SimpleDateFormat fm = new SimpleDateFormat(pattern);
			// create TimeDialog
			Dialog timeDialog = new TimePickerDialog(EatMedTimeActivity.this,
					new TimePickerDialog.OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							// txtTime.setText(hourOfDay+":"+minute);//show time
							// on txtView
							eatMedTime3.set(Calendar.HOUR_OF_DAY, hourOfDay);
							eatMedTime3.set(Calendar.MINUTE, minute);
							btnTime3.setText(fm.format(eatMedTime3.getTime()));
							Toast.makeText(EatMedTimeActivity.this,
									fm.format(eatMedTime3.getTime()),
									Toast.LENGTH_SHORT).show();
						}
					}, eatMedTime3.get(Calendar.HOUR),
					eatMedTime3.get(Calendar.MINUTE), false);// get time
			timeDialog.setTitle("Select Time");// dialog Title
			timeDialog.show();// show TimeDialog
		}
	};

	// 開關按鈕方法 (1)
	OnClickListener btnSwitch_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!btnTime.getText().equals("時間")) {// 先設定時間在給開關
				if (key1) {// 如果吃藥"開"的
					key1 = !key1;
					state1 = "1";
					String pattern1 = "yyyy-MM-dd E kk mm ss";
					SimpleDateFormat fm1 = new SimpleDateFormat(pattern1);
					Toast.makeText(EatMedTimeActivity.this, "吃藥(一)開啟",
							Toast.LENGTH_SHORT).show();
					btnSwitch.setText("已開");
					// default alarm is off if alarm is on( set it off)

				} else {// 如果吃藥"關"的
					key1 = !key1;
					state1 = "0";
					Toast.makeText(EatMedTimeActivity.this, "吃藥(一)關閉",
							Toast.LENGTH_SHORT).show();
					btnSwitch.setText("已關");
				}
			} else {
				Toast.makeText(EatMedTimeActivity.this, "先設定時間",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	// 開關按鈕方法 (2)
	OnClickListener btnSwitch2_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!btnTime2.getText().equals("時間")) {// 先設定時間在給開關
				if (key2) {// 如果吃藥"開"的
					key2 = !key2;
					state2 = "1";
					String pattern1 = "yyyy-MM-dd E kk mm ss";
					SimpleDateFormat fm1 = new SimpleDateFormat(pattern1);
					Toast.makeText(EatMedTimeActivity.this, "吃藥(二)開啟",
							Toast.LENGTH_SHORT).show();
					btnSwitch2.setText("已開");
					// default alarm is off if alarm is on( set it off)

				} else {// 如果吃藥"關"的
					key2 = !key2;
					state2 = "0";
					Toast.makeText(EatMedTimeActivity.this, "吃藥(二)關閉",
							Toast.LENGTH_SHORT).show();
					btnSwitch2.setText("已關");
				}
			} else {
				Toast.makeText(EatMedTimeActivity.this, "先設定時間",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	// 開關按鈕方法 (3)
	OnClickListener btnSwitch3_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!btnTime3.getText().equals("時間")) {// 先設定時間在給開關
				if (key3) {// 如果吃藥"開"的
					key3 = !key3;
					state3 = "1";
					String pattern1 = "yyyy-MM-dd E kk mm ss";
					SimpleDateFormat fm1 = new SimpleDateFormat(pattern1);
					Toast.makeText(EatMedTimeActivity.this, "吃藥(三)開啟",
							Toast.LENGTH_SHORT).show();
					btnSwitch3.setText("已開");
					// default alarm is off if alarm is on( set it off)

				} else {// 如果吃藥"關"的
					key3 = !key3;
					state3 = "0";
					Toast.makeText(EatMedTimeActivity.this, "吃藥(三)關閉",
							Toast.LENGTH_SHORT).show();
					btnSwitch3.setText("已關");
				}
			} else {
				Toast.makeText(EatMedTimeActivity.this, "先設定時間",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	public LinkedList<byte[]> GetByte(String name) {
		String path = "";
		FileInputStream fis = null;
		LinkedList<byte[]> bList = new LinkedList<byte[]>();
		try {
			File imageDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			path = new File(imageDir, name).toString();

			fis = new FileInputStream(path);
			byte[] bytes = new byte[1024];
			byte[] bb = null;
			int n = 0;
			while ((n = fis.read(bytes)) != -1) {
				bb = new byte[n];
				for (int i = 0; i < n; i++) {
					bb[i] = bytes[i];
				}
				bList.add(bb);
			}
			Toast.makeText(EatMedTimeActivity.this, bList.size() + "*" + path,
					Toast.LENGTH_SHORT).show();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bList;
	}
}
